using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using NTTHAO.CommonWeb;
using System.Collections.Specialized;
using NTTHAO.Web.BL.Authentication;

namespace NTTHAO.Sites.CommonSite
{
    /// <summary>
    /// Summary description for Authentication
    /// </summary>
    public static class Authentication
    {
        private static TimeSpan DEFAULT_TIMEOUT = new TimeSpan(2, 0, 0); // 2 hours

        private static string COOKIE_AUTHENTICATION_KEY = "AUTHENTICATION_ID";

        private static bool CheckAuthenticationKey(string key)
        {
            try
            {
                if (key == null || key.IndexOf("|") < 1)
                {
                    return false;
                }
                string[] keys = key.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                if (keys.Length != 2)
                {
                    return false;
                }
                User user = new User(keys[0]);
                if (user.ID < 1)
                {
                    return false;
                }
                string md5Str = WebGlobal.MD5String(user.ID + "_" + user.JoinDate.Ticks.ToString());
                return md5Str.Equals(keys[1], StringComparison.OrdinalIgnoreCase);
            }
            catch { }
            return false;
        }

        public static bool IsAuthenticated
        {
            get
            {
                try
                {
                    if (CookieUtility.SupportCookie(HttpContext.Current.Request))
                    {
                        string cookieValue = CookieUtility.GetCookieValue(Authentication.COOKIE_AUTHENTICATION_KEY, HttpContext.Current.Request);
                        bool result = Authentication.CheckAuthenticationKey(cookieValue);
                        if (!result)
                        {
                            Authentication.SignOut();
                        }
                        return result;
                        //return (CookieUtility.GetCookieValue(Authentication.COOKIE_AUTHENTICATION_KEY, HttpContext.Current.Request) != null);
                    }
                    else if (HttpContext.Current.Session[Authentication.COOKIE_AUTHENTICATION_KEY] != null)
                    {
                        return true;
                    }
                }
                catch (Exception)
                {
                }
                return false;
            }
        }

        public static string Name
        {
            get
            {
                if (!Authentication.IsAuthenticated)
                {
                    return string.Empty;
                }
                try
                {
                    if (CookieUtility.SupportCookie(HttpContext.Current.Request))
                    {
                        string cookieValue = CookieUtility.GetCookieValue(Authentication.COOKIE_AUTHENTICATION_KEY, HttpContext.Current.Request);

                        return cookieValue.Split('|')[0];
                        //return CookieUtility.GetCookieValue(Authentication.COOKIE_AUTHENTICATION_KEY, HttpContext.Current.Request);
                    }
                    else 
                    {
                        return HttpContext.Current.Session[Authentication.COOKIE_AUTHENTICATION_KEY].ToString();
                    }
                }
                catch (Exception)
                {
                }
                return string.Empty;
            }
        }

        public static void SetAuthCookie(string name, bool remember)
        {
            try
            {
                User user = new User(name);
                if (user.ID < 1)
                {
                    return;
                }
                string md5Str = WebGlobal.MD5String(user.ID + "_" + user.JoinDate.Ticks.ToString());
                string cookieValue = user.UserName + "|" + md5Str;

                DateTime timeout = DateTime.Now.Add(Authentication.DEFAULT_TIMEOUT);
                if (remember)
                {
                    timeout = DateTime.MaxValue;
                }

                CookieUtility.SetCookie(Authentication.COOKIE_AUTHENTICATION_KEY, cookieValue.Trim(), timeout, HttpContext.Current.Request, HttpContext.Current.Response);
                HttpContext.Current.Session.Add(COOKIE_AUTHENTICATION_KEY, name.Trim());
            }
            catch { }
        }

        public static void SignOut()
        {
            CookieUtility.DeleteCookie(COOKIE_AUTHENTICATION_KEY, HttpContext.Current.Request, HttpContext.Current.Response);
            HttpContext.Current.Session.Remove(COOKIE_AUTHENTICATION_KEY);
        }

        public static bool RequireAuthentication()
        {
            if (!Authentication.IsAuthenticated)
            {
                Authentication.RedirectToLoginPage();
                return false;
            }
            return true;
        }

        public static void RedirectToLoginPage()
        {
            HttpContext context = HttpContext.Current;
            context.Response.Redirect("/trang-ca-nhan/dang-nhap.html?ReturnUrl=" + context.Server.UrlEncode(context.Request.RawUrl), false);
        }

        public static void RedirectFromLoginPage()
        {
            HttpContext context = HttpContext.Current;
            
            string returnUrl = Authentication.GetRedirectUrl();
            if (returnUrl != null && returnUrl.Trim().Length > 0)
            {
                context.Response.Redirect(returnUrl, false);
            }
            else
            {
                context.Response.Redirect("/trang-ca-nhan/trang-ca-nhan.html", false);
            }
        }

        public static string GetRedirectUrl()
        {
            HttpContext context = HttpContext.Current;
            string rawUrl = context.Request.RawUrl;
            if (rawUrl.IndexOf("?") >= 0)
            {
                string[] rawSpl = rawUrl.Split(new char[] { '?' }, StringSplitOptions.RemoveEmptyEntries);
                string queryString = rawSpl[0];
                if (rawSpl.Length > 1)
                {
                    NameValueCollection nvColl = HttpUtility.ParseQueryString("?" + rawSpl[1]);
                    if (nvColl["ReturnUrl"] != null)
                    {
                        return nvColl["ReturnUrl"];
                    }
                }
            }

            return null;
        }
    }
}